package com.sanji.sjmallmodule.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.sanji.sjmallapp.MallApplication;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallconfig.ConfigConts;
import com.sanji.sjmallmanager.activity.ActivityManager;
import com.sanji.sjmallmodule.order.ShopcarFragment;
import com.sanji.sjmallmodule.goods.SearchFragment;
import com.sanji.sjmallmodule.order.MyFragment;
import com.sanji.sjmallmodule.order.ShopcarNewFragment;
import com.sanji.sjmallmodule.phoneshell.PhoneShellFragment;
import com.sanji.sjmallutils.SharePreferenceUtil;
import com.sanji.sjmallutils.Tools;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class MainActivity extends FragmentActivity {
    @BindView(R.id.MainRadioGroup)
    RadioGroup MainRadioGroup;
    @BindView(R.id.mainViewPager)
    ViewPager mainViewPager;
    private FragmentPagerAdapter fragmentPagerAdapter;
    private static List<Fragment> fragments;
    private boolean isHome = false;
    private SharePreferenceUtil myShare;
    private boolean isExit = false;
    private int groupCount=5;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        ActivityManager.getInstance().addActivity(this);
        initView();
        addFragment();
        setView();

        registerReceiver();

        setJPushAlias();

    }

    /**
     * 初始化数据
     */
    public void initView() {
        fragments = new ArrayList<>();
        mainViewPager.setPageTransformer(false, new ViewPager.PageTransformer() {

            @Override
            public void transformPage(View page, float position) {
                final float normalizedposition = Math.abs(Math.abs(position) - 1);
                page.setAlpha(normalizedposition);
            }
        });
    }

    /**
     * 加载Fragment
     */
    public void addFragment() {
        Fragment fragment = new MainFragment();
        fragments.add(fragment);

        fragment = new SearchFragment();
        fragments.add(fragment);

        fragment = new PhoneShellFragment();
        fragments.add(fragment);

        fragment = new ShopcarNewFragment();
        fragments.add(fragment);

        fragment = new MyFragment();
        fragments.add(fragment);

        fragmentPagerAdapter = new FragmentPgAdapter(getSupportFragmentManager(), fragments);
        mainViewPager.setAdapter(fragmentPagerAdapter);
//        mainViewPager.setOffscreenPageLimit(4);
    }

    /**
     * bottomRadioGroup+fragment滑动
     */
    public void setView() {
        mainViewPager.setCurrentItem(0);
        ((RadioButton) MainRadioGroup.getChildAt(0)).setChecked(true);
        MainRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkId) {
                for (int i = 0; i < groupCount; i++) {
                    if (radioGroup.getChildAt(i).getId() == checkId) {
                        mainViewPager.setCurrentItem(i);
                    }
                }
            }
        });
        mainViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            //正在滚动中
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            //状态已经改变
            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < MainRadioGroup.getChildCount(); i++) {
                    if (i == position) {
                        ((RadioButton) MainRadioGroup.getChildAt(i)).setChecked(true);
                    } else {
                        ((RadioButton) MainRadioGroup.getChildAt(i)).setChecked(false);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (((RadioButton) MainRadioGroup.getChildAt(0)).isChecked()) {
                    exit();
                } else {
                    ((RadioButton) MainRadioGroup.getChildAt(0)).setChecked(true);
                    mainViewPager.setCurrentItem(0);
                }
                break;
        }
        return false;
    }

    /**
     * 连着两次点击退出登录
     */
    private void exit() {
        if (!isExit) {
            isExit = true;
            Tools.toastTools(this, getString(R.string.main_logout_toast));
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            ActivityManager.AppExit();
        }
    }

    //----定义广播
    private void registerReceiver() {
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConfigConts.ACTION_FRAGMENT_PAGER);
        registerReceiver(msetPageReceiver, mFilter);
    }


    private BroadcastReceiver msetPageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConfigConts.ACTION_FRAGMENT_PAGER)) {
                int index = intent.getIntExtra("index", 0);
                ((RadioButton) MainRadioGroup.getChildAt(index)).setChecked(true);
            }
        }
    };


    @Override
    protected void onDestroy() {
        unregisterReceiver(msetPageReceiver);
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);//统计时长
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);//统计时长
    }

    private void setJPushAlias(){
        String uid = MallApplication.myShare.getString(ConfigConts.USER_ID,"");
        if (!"".equals(uid)){
            Set<String> tags = new HashSet<String>();
            tags.add(uid);
            JPushInterface.setAliasAndTags(MainActivity.this, uid, tags, new TagAliasCallback() {
                @Override
                public void gotResult(int i, String s, Set<String> set) {
//                    Tools.toastTools(MainActivity.this,i+"");
                }
            });
        }

    }
}
